package com.enation.app.javashop.consumer.job.execute.impl;

import com.alibaba.fastjson.JSON;
import com.enation.app.javashop.consumer.job.execute.EveryDayExecute;
import com.enation.app.javashop.consumer.job.execute.EveryHourExecute;
import com.enation.app.javashop.core.base.CachePrefix;
import com.enation.app.javashop.core.client.goods.GoodsClient;
import com.enation.app.javashop.core.member.model.dos.Member;
import com.enation.app.javashop.core.member.model.dto.MemberQueryParam;
import com.enation.app.javashop.core.member.service.MemberManager;
import com.enation.app.javashop.core.promotion.luck.model.dos.LuckPrizeDO;
import com.enation.app.javashop.core.promotion.luck.model.dos.LuckRecordDO;
import com.enation.app.javashop.core.promotion.shetuan.model.dos.ShetuanDO;
import com.enation.app.javashop.core.promotion.shetuan.model.enums.ShetuanStatusEnum;
import com.enation.app.javashop.core.promotion.shetuan.service.ShetuanOperateManager;
import com.enation.app.javashop.core.trade.order.model.dos.OrderDO;
import com.enation.app.javashop.core.trade.order.model.enums.ShipStatusEnum;
import com.enation.app.javashop.core.trade.order.model.vo.OrderSkuVO;
import com.enation.app.javashop.core.wms.model.dos.WmsOrderDO;
import com.enation.app.javashop.core.wms.model.dos.WmsOrderItemsDO;
import com.enation.app.javashop.core.wms.model.enums.WmsOrderStatusEnums;
import com.enation.app.javashop.framework.cache.Cache;
import com.enation.app.javashop.framework.database.DaoSupport;
import com.enation.app.javashop.framework.database.Page;
import com.enation.app.javashop.framework.util.DateUtil;
import com.enation.app.javashop.framework.util.JsonUtil;
import com.enation.app.javashop.framework.util.SqlUtil;
import com.enation.app.javashop.framework.util.StringUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 社团团购活动定时开始结束
 */
@Component
public class WmsJob implements EveryDayExecute {

    protected final Log logger = LogFactory.getLog(this.getClass());


    @Autowired
    @Qualifier("tradeDaoSupport")
    private DaoSupport daoSupport;

    @Autowired
    private JdbcTemplate jdbcTemplate;


    /**
     * 每天执行 00：00：00
     */
    @Override
    public void everyDay() {

        try {
            LocalDate localDate = LocalDate.now().plusDays(-1);
            Long startTime = LocalDateTime.of(localDate, LocalTime.MIN).toEpochSecond(ZoneOffset.UTC);
            Long endTime = LocalDateTime.of(localDate, LocalTime.MAX).toEpochSecond(ZoneOffset.UTC);
            List<LuckRecordDO> luckRecordDOS = daoSupport.queryForList("SELECT * FROM es_luck_record WHERE prize_type=1 and create_time>"+startTime+" and create_time<"+endTime+" ORDER BY member_id", LuckRecordDO.class);
            if (CollectionUtils.isEmpty(luckRecordDOS)) {
                return;
            }
            // 第一步查询中奖信息
            Map<Integer, List<LuckRecordDO>> luckRecordMap = luckRecordDOS.stream().collect(Collectors.toMap(LuckRecordDO::getMemberId, luckRecordDO -> Lists.newArrayList(luckRecordDO),
                    (List<LuckRecordDO> newValueList, List<LuckRecordDO> oldValueList) -> {
                        oldValueList.addAll(newValueList);
                        return oldValueList;
                    }));

            // 第二步查询中奖商品关联出库单
            Set<Integer> memberIds = luckRecordMap.keySet();
            Integer[] memberIdsArray = memberIds.toArray(new Integer[memberIds.size()]);
            List<Object> term = new ArrayList<>();
            String str = SqlUtil.getInSql(memberIdsArray, term);
            List<Map> wmsOrderMember = daoSupport.queryForList("SELECT od.member_id,wo.delivery_id,wo.order_sn, wo.items_json FROM es_order od " +
                            "LEFT JOIN wms_order wo ON od.sn=wo.order_sn " +
                            " WHERE od.create_time>"+startTime+" and od.create_time<"+endTime+"  and  od.order_status='PAID_OFF' " +
                            "and wo.delivery_id is NOT null  and od.member_id in ("+str+")" +
                            "  GROUP BY od.member_id;",
                    term.toArray());

            // 第三步 分发出库中奖商品
            List<WmsOrderItemsDO> wmsOrderItems = new ArrayList<>();

            List<Object[]> batchArgs = new ArrayList<>();
            for (Map map : wmsOrderMember) {
                Integer memberId = (Integer) map.get("member_id");
                String orderSn = (String) map.get("order_sn");
                Integer wmsOrderId = (Integer) map.get("delivery_id");

                List<OrderSkuVO>  skuListOrigin = JsonUtil.jsonToList((String) map.get("items_json"), OrderSkuVO.class);
                List<LuckRecordDO> luckRecordGoods = luckRecordMap.get(memberId);
                if(CollectionUtils.isEmpty(luckRecordGoods)){
                    continue;
                }

                for (LuckRecordDO luckRecordGood : luckRecordGoods) {
                    String goodsName = "【奖品】:" + luckRecordGood.getPrizeName();
                    WmsOrderItemsDO wmsOrderItemsDO = new WmsOrderItemsDO();
                    wmsOrderItemsDO.setOrderSn(orderSn);
                    wmsOrderItemsDO.setWmsOrderId(wmsOrderId);
                    wmsOrderItemsDO.setName(goodsName);
                    wmsOrderItemsDO.setShipNum(1);
                    wmsOrderItemsDO.setShipStatus(ShipStatusEnum.SHIP_NO.value());
                    wmsOrderItemsDO.setGoodsId(0);
                    wmsOrderItemsDO.setSkuId(0);
                    wmsOrderItemsDO.setCatId(0);

                    wmsOrderItems.add(wmsOrderItemsDO);

                    OrderSkuVO orderSkuVO = new OrderSkuVO();
                    orderSkuVO.setNum(1);
                    orderSkuVO.setName(goodsName);
                    orderSkuVO.setPurchasePrice(0.00);
                    orderSkuVO.setSubtotal(0.00);
                    orderSkuVO.setCatId(0);
                    orderSkuVO.setSkuId(0);
                    orderSkuVO.setGoodsId(0);
                    orderSkuVO.setActualPayTotal(0.00);
                    skuListOrigin.add(orderSkuVO);
                }

                // 更新出库单数据
                batchArgs.add(new Object[]{
                        JSON.toJSONString(skuListOrigin),wmsOrderId});
            }
            if(!CollectionUtils.isEmpty(wmsOrderItems)){
                this.daoSupport.batchInsert("wms_order_items",wmsOrderItems);
            }
            if(!CollectionUtils.isEmpty(batchArgs)){
                this.jdbcTemplate.batchUpdate("UPDATE wms_order SET items_json=?  WHERE delivery_id = ? ", batchArgs);
            }

        } catch (Exception e) {
            this.logger.error("每日中奖商品进入出库序列：", e);
        }
    }


}
